package top.lingkang.fas.admin.config;

import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import top.lingkang.fas.common.dto.R;
import top.lingkang.finalvalidated.error.ValidatedException;

/**
 * @author lingkang
 * created by 2025/7/20 2:48
 */
@Slf4j
@Component
public class GlobalExceptionHandler implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (ValidatedException | IllegalArgumentException e) {
            log.error("校验错误：{} {}  {}: {}", ctx.method(), ctx.path(), e.getClass().getName(), e.getMessage());
            ctx.outputAsJson(R.fail(e.getMessage()).toJson());
        } catch (StatusException e) {
            log.warn("请求状态异常：{}", e.getMessage());
            if (e.getCode() == 404) {
                ctx.outputAsJson(R.fail("not found url: " + ctx.path()).toJson());
            } else if (e.getCause() instanceof ClassCastException) {
                ctx.outputAsJson(R.fail("入参错误").toJson());
            }
        } catch (Exception e) {
            log.error("全局异常：{}", e.getMessage(), e);
            ctx.outputAsJson(R.fail("服务处理失败").toJson());
        }
    }
}
